"use strict";
require([
    './dev/layer',
    'polyfill',
    './dev/nav',
    'html2canvas',
    'text!tpl/upList.hbs',
    'text!tpl/view.hbs',
    './conf/baseConfig',
    './dev/helper',
    './dev/http'
], function (layer, polyfill, nav, html2canvas, upList, view, baseConfig, helper, http) {
    //layer.loadLayer();
    nav.showNav();

    const target = "demo";

    //layer.previewTxt(formSet, "sumitbox", formConf);

    layui.use(['layer', 'layedit', 'laypage', 'form', 'laydate'], function () {
        const  layedit = layui.layedit,
               laypage = layui.laypage,
               $ = layui.jquery,
               arr =[],
               imgs = [],
               contents =[];
        let num=0;
        layedit.set({
          uploadImage: {
          url: `${baseConfig.serUrl}/batch/uploads` //接口url
          ,type: 'post' //默认post
          }
        });
        const index = layedit.build(target,{
          height:528
        }); //建立编辑器
        $(document).on("click", "#btn-edit", function () {
          const content = layedit.getContent(index);
             console.log(content)
             contents.push(content)
            $("#textPdf").html(content)
        });

        //创建文档
        $(document).on("click", "#buildImg", function () {
            console.log(contents)
            html2canvas(document.querySelector("#textBox")).then(canvas => {
                //console.log(canvas.toDataURL('image/png'));
                const dataURLtoFile = function (dataurl, filename) {//将base64转换为文件
                  var arr = dataurl.split(','),
                        mime = arr[0].match(/:(.*?);/)[1],
                        bstr = atob(arr[1]),
                        n = bstr.length,
                        u8arr = new Uint8Array(n);
                    while (n--) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    return new File([u8arr], filename, { type: mime });
                };

                num+=1
                const txt = sessionStorage.getItem("filename");
                const prefix = `${txt}${num}`
                let fileName = `${prefix}.png`
                const file = dataURLtoFile(canvas.toDataURL('image/png'), fileName)
                arr.push(file)

                var timestamp = Date.parse(new Date());
                //把截取到的图片替换到a标签的路径下载
                $("#down1").attr('href', canvas.toDataURL());
                //下载下来的图片名字
                $("#down1").attr('download', timestamp + '.png');
            });
            $('#LAY_layedit_1').contents().find('body').html('');
        });

        //提交文档到服务端
      $(document).on("click", "#saveEdit", function () {
        //sessionStorage.setItem("contents",contents)

        const formData = new FormData()

        for(let i=0; i<arr.length;i++){
          formData.append('file', arr[i]);
        }

        $.ajax({
          url: `${baseConfig.serUrl}/batch/upload`,
          type: "post",
          data: formData,
          contentType: false,
          processData: false,
          mimeType: "multipart/form-data",
          success: function (res) {
            console.log(res)
            const result = JSON.parse(res);
            console.log(result)
            if(result.data){
              $(".show-edit").css("display","none")
              $(".reset-dit").css("display","inline-block")
              $("#leftBox").append(`<div id="preview" class="animated zoomIn"></div>`)
            }
            const data = {
              serUrl:baseConfig.serUrl,
                list:result.data
            };
            layui.each(data.list, function (index, item) {
                 let elt = `${data.serUrl}${item.src}`
                 imgs.push(elt)
            });
            laypage.render({  //动态分页
              elem: 'pagenation',
              count: data.list.length,
              limit: 6,
              jump: function(obj){
                let  thisData = data.list.concat().splice(obj.curr*obj.limit - obj.limit, obj.limit);
                const pages = {
                  serUrl:data.serUrl,
                  list:thisData
                };
                layer.setlayTpl("laytpl","prew", upList, pages)
              }
            });
            layer.setlayTpl("laytpl","preview", view, data)
          },
          error: function (data) {
            console.log(data);
          }
        });
      });

      $(document).on("click", ".current-page", function(){
           let viewHtml = $(this).html(),
                preview  = $("#preview");
                preview.html(viewHtml)
          //  $("#preview").append('<bottom>修改</bottom>')
      })

      $(document).on("click", "#txtsetUp", function(){
        sessionStorage.setItem("imgs",imgs)
        window.open("bookSetup.html", "_self")
      })

    });






});
